package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Author: Pepsi
 * Date: 2023/7/29
 * Desc:
 */
public class Flink12_Rich {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStreamSource<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_1", 1L, 10),
                new WaterSensor("sensor_2", 1L, 20),
                new WaterSensor("sensor_1", 1L, 30),
                new WaterSensor("sensor_1", 1L, 40),
                new WaterSensor("sensor_2", 1L, 50)
        );

        // 假设每来一个数据。我要从数据库里面查一次，然后根据查询的结果来决定做什么操作
        stream
                // 所有的函数都有rich版本，process没有，因为它本身就有这两个方法了
                .map(new RichMapFunction<WaterSensor, String>() {
                    // open close执行几次是和并行度有关的
                    // open 在所有的初始化已经完成，环境已经可用的情况下，当程序启动的时候，每个并行度执行一次
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        System.out.println("open方法被执行了");
                    }
                    // 当程序关闭的时候，每个并行度执行一次
                    @Override
                    public void close() throws Exception {
                        System.out.println("close方法被执行了");
                    }

                    @Override
                    public String map(WaterSensor value) throws Exception {
                        System.out.println("map方法执行了");
                        return value+"";
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
